import { ChangeSwitchFnc, GetUserFnc, RemoveUserFnc } from '@/services/users';
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Switch } from 'antd';
import { useRef, useState } from 'react';
import AddEdit from './components/AddEdit';
import GiveRole from './components/GiveRole';
import { itemType } from './type';

const User = () => {
  const actionRef: any = useRef<ActionType>();
  const [modal, contextHolder] = Modal.useModal();

  const [paramsAll, setParamsAll] = useState({ query: '' });
  const [pageSize, setPageSize] = useState(2); // table 每页显示的条数
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [isModalOpen, setIsModalOpen] = useState(false); // 添加修改用户的盒子
  const [openType, setOpenType] = useState(''); // 要么是add 要么是edit 打开盒子传值 关闭盒子不传值
  const [openID, setOpenID] = useState(''); // 打开编辑盒子获得的ID
  const [roleModalOpen, setRoleModalOpen] = useState(false); // 分配角色盒子
  const [roleName, setRoleName] = useState('');
  const [roleDesc, setRoleDesc] = useState('');

  // switch 改变状态
  const changeSwitch = async (id: number, status: boolean) => {
    const res = await ChangeSwitchFnc({ id: id, state: status });
    if (res.meta.status === 200)
      message.open({ type: 'success', content: '更新成功', duration: 1.5 });
  };

  // table数据初始化
  const getData = async (params: any) => {
    const res = await GetUserFnc({
      query: params.query,
      pagenum: current,
      pagesize: params.pageSize,
    });
    let arr: [] = [];
    arr = res.data.users.map((item: itemType, index: number) => {
      return {
        key: index + 1,
        id: item.id,
        username: item.username,
        email: item.email,
        mobile: item.mobile,
        role_name: item.role_name,
        mg_state: item.mg_state,
      };
    });
    setTotal(res.data.total);
    return {
      data: arr,
      success: res.meta.status === 200,
      total: res.data.total,
    };
  };

  // 打开添加 修改 用户盒子 给子组件使用
  const openBox = (flag: boolean, ...args: any[]) => {
    setIsModalOpen(flag);
    setOpenType(args[0]);
    setOpenID(args[1]);
  };

  // 删除用户
  const deleteUser = (id: number) => {
    modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除用户, 是否继续?',
      onOk: async () => {
        const res = await RemoveUserFnc(id);
        if (res.meta.status === 200) {
          message.open({
            type: 'success',
            content: '删除成功',
            duration: 1.5,
            onClose: () => {
              if (total % pageSize === 1) {
                setCurrent(current - 1);
              }
              actionRef.current?.reload();
            },
          });
        }
      },
    });
  };

  // 分配用户盒子
  const openRoleBox = (flag: boolean, ...args: any) => {
    setRoleModalOpen(flag);
    setOpenID(args[0]);
    setRoleName(args[1]);
    setRoleDesc(args[2]);
  };

  const columns: any = [
    { dataIndex: 'key', key: 'id', width: 50 },
    { title: '姓名', key: 'username', dataIndex: 'username', width: 100 },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
      width: 170,
      ellipsis: true,
      tooltip: '',
    },
    {
      title: '电话',
      key: 'mobile',
      dataIndex: 'mobile',
      width: 130,
      ellipsis: true,
      tooltip: '',
    },
    {
      title: '角色',
      key: 'role_name',
      dataIndex: 'role_name',
      width: 120,
      ellipsis: true,
      tooltip: '',
    },
    {
      title: '状态',
      key: 'mg_state',
      dataIndex: 'mg_state',
      width: 80,
      render: (value: boolean, item: { id: number; mg_state: boolean }) => {
        return (
          <Switch
            defaultChecked={item.mg_state}
            onChange={(checked: boolean) => changeSwitch(item.id, checked)}
          />
        );
      },
    },
    {
      title: '操作',
      width: 250,
      render: (info: { id: number; username: string; role_name: string }) => {
        return (
          <>
            <Button
              type="primary"
              size="small"
              icon={<EditOutlined />}
              onClick={() => openBox(true, 'edit', info.id)}
            >
              编辑
            </Button>
            <Button
              type="primary"
              danger
              size="small"
              icon={<DeleteOutlined />}
              onClick={() => deleteUser(info.id)}
              style={{ margin: '0 6px 0' }}
            >
              删除
            </Button>
            <Button
              color="yellow"
              variant="solid"
              size="small"
              icon={<UnorderedListOutlined />}
              onClick={() =>
                openRoleBox(true, info.id, info.username, info.role_name)
              }
            >
              设置
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <>
      {contextHolder}
      <PageContainer
        header={{
          title: '',
          breadcrumb: { items: [{ title: '用户管理' }, { title: '用户列表' }] },
        }}
      >
        <ProTable
          columns={columns}
          actionRef={actionRef}
          rowKey={(record) => record.id}
          params={paramsAll}
          request={async (params) => getData(params)}
          scroll={{ x: 500 }}
          bordered
          search={false}
          toolbar={{
            search: {
              onSearch: (val) => setParamsAll({ query: val }),
              placeholder: '请输入用户名',
              allowClear: true,
            },
            actions: [
              <Button
                type="primary"
                key={1}
                onClick={() => openBox(true, 'add')}
              >
                添加用户
              </Button>,
            ],
          }}
          onChange={({ current }: any) => setCurrent(current)}
          pagination={{
            pageSize: pageSize,
            showSizeChanger: true,
            pageSizeOptions: [2, 5, 10],
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </PageContainer>

      {/* 添加修改用户盒子  */}
      <AddEdit
        isModalOpen={isModalOpen}
        openBox={openBox}
        openType={openType}
        openID={openID}
        actionRef={actionRef}
      />

      {/* 分配角色盒子 */}
      <GiveRole
        roleModalOpen={roleModalOpen}
        openRoleBox={openRoleBox}
        roleName={roleName}
        roleDesc={roleDesc}
        actionRef={actionRef}
        openID={openID}
      />
    </>
  );
};

export default User;
